package com.example.micro_property_springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.micro_property_springboot.pojo.AssetCheckItem;
import com.example.micro_property_springboot.pojo.DTO.request.AssetCheckItemRequest;
import com.example.micro_property_springboot.pojo.VO.PageResult;
import com.example.micro_property_springboot.pojo.VO.Result;
import com.example.micro_property_springboot.service.AssetCheckItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/check-plan/{planId}/items")
@Tag(name = "盘点明细管理", description = "资产盘点明细相关操作")
public class AssetCheckItemController {

    @Autowired
    private AssetCheckItemService assetCheckItemService;

    /**
     * 分页查询盘点明细列表
     */
    @GetMapping
    @Operation(summary = "分页查询盘点明细列表", description = "根据盘点计划ID分页查询资产盘点明细列表")
    public Result<PageResult<AssetCheckItem>> getAssetCheckItems(
            @PathVariable Long planId,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String checkStatus) {
        log.info("分页查询盘点明细列表，计划ID: {}, 页码: {}, 页大小: {}, 状态: {}",
                planId, pageNum, pageSize, checkStatus);

        try {
            // 设置分页参数
            Page<AssetCheckItem> page = new Page<>(pageNum, pageSize);

            // 设置条件查询
            QueryWrapper<AssetCheckItem> wrapper = new QueryWrapper<>();
            wrapper.eq("plan_id", planId);
            if (checkStatus != null && !checkStatus.isEmpty()) {
                wrapper.eq("check_status", checkStatus);
            }
            wrapper.orderByDesc("create_time");

            // 执行查询
            Page<AssetCheckItem> itemPage = assetCheckItemService.page(page, wrapper);

            // 转换为自定义的PageResult
            PageResult<AssetCheckItem> pageResult = new PageResult<>();
            pageResult.setTotal(itemPage.getTotal());
            pageResult.setRows(itemPage.getRecords());

            log.info("成功获取{}个盘点明细，计划ID: {}", itemPage.getRecords().size(), planId);
            return Result.success("查询成功", pageResult);
        } catch (Exception e) {
            log.error("分页查询盘点明细列表失败，计划ID: {}, 错误信息: {}", planId, e.getMessage(), e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取盘点明细详情
     */
    @GetMapping("/{itemId}")
    @Operation(summary = "获取盘点明细详情", description = "根据盘点明细ID获取资产盘点明细详情")
    public Result<AssetCheckItem> getAssetCheckItemById(
            @PathVariable Long planId,
            @PathVariable Long itemId) {
        log.info("获取盘点明细详情，计划ID: {}, 明细ID: {}", planId, itemId);

        try {
            AssetCheckItem item = assetCheckItemService.getById(itemId);
            if (item == null) {
                log.warn("盘点明细不存在，明细ID: {}", itemId);
                return Result.error("盘点明细不存在");
            }

            // 验证明细是否属于指定的盘点计划
            if (!item.getPlanId().equals(planId)) {
                log.warn("明细不属于指定的盘点计划，明细ID: {}, 计划ID: {}, 明细的计划ID: {}",
                        itemId, planId, item.getPlanId());
                return Result.error("明细不属于指定的盘点计划");
            }

            log.info("成功获取盘点明细详情，明细ID: {}", itemId);
            return Result.success("查询成功", item);
        } catch (Exception e) {
            log.error("获取盘点明细详情失败，明细ID: {}, 错误信息: {}", itemId, e.getMessage(), e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 标记资产为已盘点
     */
    @PostMapping("/check")
    @Operation(summary = "标记资产为已盘点", description = "根据资产盘点明细ID标记资产为已盘点")
    public Result<AssetCheckItem> checkAsset(
            @PathVariable Long planId,
            @Valid @RequestBody AssetCheckItemRequest request) {
        log.info("标记资产为已盘点，计划ID: {}, 请求: {}", planId, request);

        try {
            Long userId = getCurrentUserId();
            AssetCheckItem item = assetCheckItemService.checkAsset(planId, request, userId);
            log.info("成功标记资产为已盘点，明细ID: {}", item.getId());
            return Result.success("标记成功", item);
        } catch (Exception e) {
            log.error("标记资产为已盘点失败，计划ID: {}, 错误信息: {}", planId, e.getMessage(), e);
            return Result.error("标记失败：" + e.getMessage());
        }
    }

    /**
     * 批量标记资产为已盘点
     */
    @PostMapping("/batch-check")
    @Operation(summary = "批量标记资产为已盘点", description = "批量标记资产盘点明细为已盘点")
    public Result<List<AssetCheckItem>> batchCheckAssets(
            @PathVariable Long planId,
            @Valid @RequestBody List<AssetCheckItemRequest> requests) {
        log.info("批量标记资产为已盘点，计划ID: {}, 请求数量: {}", planId, requests.size());

        try {
            Long userId = getCurrentUserId();
            List<AssetCheckItem> items = assetCheckItemService.batchCheckAssets(planId, requests, userId);
            log.info("成功批量标记{}个资产为已盘点，计划ID: {}", items.size(), planId);
            return Result.success("批量标记成功", items);
        } catch (Exception e) {
            log.error("批量标记资产为已盘点失败，计划ID: {}, 错误信息: {}", planId, e.getMessage(), e);
            return Result.error("批量标记失败：" + e.getMessage());
        }
    }

    /**
     * 重置盘点状态
     */
    @PostMapping("/reset")
    @Operation(summary = "重置盘点状态", description = "重置指定盘点计划的所有盘点明细状态")
    public Result<Void> resetCheckStatus(@PathVariable Long planId) {
        log.info("重置盘点状态，计划ID: {}", planId);

        try {
            assetCheckItemService.resetCheckStatus(planId);
            log.info("成功重置盘点状态，计划ID: {}", planId);
            return Result.success("重置成功");
        } catch (Exception e) {
            log.error("重置盘点状态失败，计划ID: {}, 错误信息: {}", planId, e.getMessage(), e);
            return Result.error("重置失败：" + e.getMessage());
        }
    }

    /**
     * 删除盘点明细
     */
    @DeleteMapping("/{itemId}")
    @Operation(summary = "删除盘点明细", description = "根据盘点明细ID删除资产盘点明细")
    public Result<Void> deleteAssetCheckItem(
            @PathVariable Long planId,
            @PathVariable Long itemId) {
        log.info("删除盘点明细，计划ID: {}, 明细ID: {}", planId, itemId);

        try {
            AssetCheckItem item = assetCheckItemService.getById(itemId);
            if (item == null) {
                log.warn("盘点明细不存在，明细ID: {}", itemId);
                return Result.error("盘点明细不存在");
            }

            // 验证明细是否属于指定的盘点计划
            if (!item.getPlanId().equals(planId)) {
                log.warn("明细不属于指定的盘点计划，明细ID: {}, 计划ID: {}, 明细的计划ID: {}",
                        itemId, planId, item.getPlanId());
                return Result.error("明细不属于指定的盘点计划");
            }

            boolean result = assetCheckItemService.removeById(itemId);
            if (result) {
                log.info("成功删除盘点明细，明细ID: {}", itemId);
                return Result.success("删除成功");
            } else {
                log.error("删除盘点明细失败，明细ID: {}", itemId);
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除盘点明细异常，明细ID: {}, 错误信息: {}", itemId, e.getMessage(), e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取盘点进度
     */
    @GetMapping("/progress")
    @Operation(summary = "获取盘点进度", description = "根据盘点计划ID获取资产盘点进度")
    public Result<Map<String, Integer>> getCheckProgress(@PathVariable Long planId) {
        log.info("获取盘点进度，计划ID: {}", planId);

        try {
            Map<String, Integer> progress = assetCheckItemService.getCheckProgress(planId);
            log.info("成功获取盘点进度，计划ID: {}", planId);
            return Result.success("查询成功", progress);
        } catch (Exception e) {
            log.error("获取盘点进度失败，计划ID: {}, 错误信息: {}", planId, e.getMessage(), e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取盘点统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取盘点统计信息", description = "根据盘点计划ID获取资产盘点统计信息")
    public Result<Map<String, Object>> getCheckStatistics(@PathVariable Long planId) {
        log.info("获取盘点统计信息，计划ID: {}", planId);

        try {
            Map<String, Object> statistics = assetCheckItemService.getCheckStatistics(planId);
            log.info("成功获取盘点统计信息，计划ID: {}", planId);
            return Result.success("查询成功", statistics);
        } catch (Exception e) {
            log.error("获取盘点统计信息失败，计划ID: {}, 错误信息: {}", planId, e.getMessage(), e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户ID
     * TODO: 实现从认证信息中获取当前用户ID
     * @return 当前用户ID
     */
    private Long getCurrentUserId() {
        // 这里仅为示例，实际需要从Spring Security认证信息中获取
        // 例如：SecurityContextHolder.getContext().getAuthentication().getPrincipal()
        return 1L;
    }
}